<template>
  <div style="width: 30%">
    <el-upload
      :disabled="!btnVisible"
      :action="uploadAction"
      :headers="uploadHeaders"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :file-list="imageList"
      :before-upload="beforeAvatarUpload"
    >
      <el-button v-if="btnVisible" size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script setup>
import $cookie from 'vue-cookies'
import {ElMessage} from 'element-plus'

const uploadHeaders = {Authorization: $cookie.get('Authorization')}
const uploadAction = http.adornUrl('/admin/file/upload/file')
const props = defineProps({
  modelValue: {
    default: '',
    type: String
  },
  btnVisible: {
    default: true
  }
})
const emit = defineEmits(['update:modelValue', 'upload-success'])
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL
const onlineViewUrl = import.meta.env.VITE_ONLINE_VIEW

const imageList = computed(() => {
  const res = []
  if (props.modelValue) {
    const imageArray = props.modelValue
    for (let i = 0; i < imageArray.length; i++) {
      res.push({
        url: resourcesUrl + imageArray[i]['url'],
        name: imageArray[i]['name'],
        response: imageArray[i]
      })
    }
  }
  emit('update:modelValue', props.modelValue)
  return res
})

/**
 * 图片上传
 */
// eslint-disable-next-line no-unused-vars
const handleUploadSuccess = (response, file, fileList) => {
  const pics = fileList.map(file => {
    if (typeof file.url === 'string') {
      return file.response
    }
    return file.response.data
  })
  emit('update:modelValue', pics)
}

/**
 * 限制图片上传大小
 */
const beforeAvatarUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
  }
  return isLt2M
}
const handleRemove = (file, fileList) => {
  const pics = fileList.map(file => {
    if (typeof file.url === 'string') {
      return file.response
    }
    return file.response.data
  })
  emit('update:modelValue', pics)
}

const handlePictureCardPreview = (file) => {
  window.open((onlineViewUrl + file.url), '_blank')
}

</script>
